package golf.stockdata.connector.tfex;

import golf.stockdata.connector.tfex.dataobject.set50.AllContractsTradingInfo_Type;
import golf.stockdata.connector.tfex.dataobject.set50.ContractTradingInfo_Type;
import golf.stockdata.connector.tfex.dataobject.set50.TFEXDataObject_Type;
import golf.stockdata.framework.exception.AbilityInitializationException;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Properties;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.apache.log4j.Logger;
import org.htmlparser.beans.StringBean;

public class TFEX_SET50ConnectorImpl implements TFEXConnector {
	
	private static Logger logger = Logger.getLogger(TFEX_SET50ConnectorImpl.class);

	private ArrayList<String> urlList = new ArrayList<String>();
	private ArrayList<String> tfexList = new ArrayList<String>();
	private ArrayList<String> keywords = new ArrayList<String>();
	
	public void initializeAbility(Properties props)
			throws AbilityInitializationException {
		
		logger.debug(">>> initializeAbility");
		
		for(int i=1;;i++){
			String tmpTfexName = props.getProperty("tfex.name.".concat(String.valueOf(i)));
			String tmpURL = props.getProperty("tfex.URL.".concat(String.valueOf(i)));
			String keyword = props.getProperty("tfex.keyword.".concat(String.valueOf(i)));
			if(tmpTfexName != null
					&& !tmpTfexName.isEmpty()
					&& tmpURL != null
					&& !tmpURL.isEmpty()
					&& keyword != null
					&& !keyword.isEmpty()){
				urlList.add(tmpURL);
				tfexList.add(tmpTfexName);
				keywords.add(keyword);
			}else{
				break;
			}
		}
		if(urlList.size() <= 0){
			logger.debug(">>> initializeAbility(throwing AbilityInitializationException)");
			 throw new AbilityInitializationException("URL is missing");
		}
		
		logger.debug("<<< initializeAbility");
		
	}

	public TFEXDataObject_Type call() {
		
		logger.debug(">>> call");
		
		AllContractsTradingInfo_Type data = new AllContractsTradingInfo_Type();
        
		for(int j=0;j<urlList.size();j++){
			
			String url=urlList.get(j);
			String tfexName=tfexList.get(j);
		
			StringBean sb = new StringBean ();
	        sb.setLinks (false);
	        sb.setReplaceNonBreakingSpaces (true);
	        sb.setCollapse (true);
	        sb.setURL (url);
	        
	        String[] outputLines = sb.getStrings().split("\\n");
//	        System.out.println(sb.getStrings());
	        
	        for(int i=0; i < outputLines.length; i++){
	        	
	        	logger.debug("outputLines[i]:" + outputLines[i]);

	        	if(outputLines[i].indexOf(keywords.get(j)) >= 0
	        			&& outputLines[i].indexOf(keywords.get(j).concat(" ")) < 0){
	        		
	        		logger.debug("Processing data...");
	        		
	        		ContractTradingInfo_Type contractInfo = new ContractTradingInfo_Type();
	        		contractInfo.setTfexName(tfexName);
	        		contractInfo.setSymbol(outputLines[i]);
	        		contractInfo.setContractMonth(outputLines[++i]);
	        		contractInfo.setOpen(outputLines[++i]);
	        		contractInfo.setHigh(outputLines[++i]);
	        		contractInfo.setLow(outputLines[++i]);
	        		contractInfo.setBid(outputLines[++i]);
	        		contractInfo.setOffer(outputLines[++i]);
	        		contractInfo.setLast(outputLines[++i]);
	        		contractInfo.setChg(outputLines[++i]);
	        		contractInfo.setVol(outputLines[++i]);
	        		contractInfo.setoI(outputLines[++i]);
	        		contractInfo.setPriorSP(outputLines[++i]);
	        		contractInfo.setsP(outputLines[++i]);
	        		
	        		debug(contractInfo);
	        		
	        		data.getContractList().add(contractInfo);
	        	}
	        }
	        
		}
		
		logger.debug("<<< call");
		return data;
	}
	
	private void debug(ContractTradingInfo_Type contractInfo){
		
		if(logger.isDebugEnabled()){
			try {
				JAXBContext JAXB_CONTEXT = JAXBContext.newInstance(AllContractsTradingInfo_Type.class);
	    		Marshaller m = JAXB_CONTEXT.createMarshaller();
	    		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
	    		StringWriter strWrt = new StringWriter();
	    		m.marshal(contractInfo, strWrt);
	    		logger.debug("ContractTradingInfo:" + strWrt.toString());

			} catch (JAXBException e) {
				logger.warn(e);
			}
		}
		
	}

}
